<template>
  <view class="content">
    <view class="top">
      <view class="navbar" :style="{ height: navBarHeight + 'px' }"> </view>
	  <view class="page-title">找牛人</view>
      <view class="mp-search">
        <!-- <view class="location" @click="toSelectCity">
					<image :src="$mConfig.imageUrl + '/image/icon-add.png'" class="add-icon"></image>
					<text class="city ellipsis-oneline">{{ location.city }}</text>
					<image :src="$mConfig.imageUrl + '/image/icon-xl1.png'" class="icon-xl1"></image>
				</view> -->
        <view class="mp-search-input" @click="search">
          <text>请输入职位名称</text>
          <image
            :src="imgUrl + '/image/icon-search.png'"
            class="icon-search"
          ></image>
        </view>
      </view>
      <view class="tabs-cont">
        <!-- <view class="tabs-box">
					<view class="tab-item" :class="selectTab===item.value?'selectTab':''" v-for="item in tabs"
						:key="item.value" @click="changeTab(item.value)">
						{{item.label}}
					</view>
				</view> -->
        <view class="right-cont">
          <view class="select-item" @click="toSelectCity">
            <template v-if="savedLocation && savedLocation.formatted_address">
              {{ savedLocation.formatted_address }}<image :src="imgUrl + '/image/icon-xl.png'"></image>
            </template>
            <template v-else>
              城市地区<image :src="imgUrl + '/image/icon-xl.png'"></image>
            </template>
          </view>
          <view class="select-item" @click="toPost()">
            选择工种<image :src="imgUrl + '/image/icon-xl.png'"></image>
          </view>
        </view>
      </view>
    </view>
    <view :style="{ 'margin-top': topHeight + 'px' }" class="index-cont">
      <template v-if="hasLogin == false || (hasLogin && userInfo)">
        <!-- <view >
          <yzb-grid :columnNum="5" :data="grid"
						show-border="false" @click="handleClickGrid"></yzb-grid></view> -->
        <user-list
          fromType="1"
          v-for="(item, index) in 5"
          :key="index"
          @gotoPer="gotoPer"
          @click.native="gotoPer"
        />
        <!-- <yzb-position :positions="list" @click="positionDetail" v-if="selectTab===1"></yzb-position> -->
        <!-- <company-list :list="companyList" v-else/> -->
      </template>
      <view class="load-more-box">
        <uni-load-more
          v-if="status == '请求中'"
          status="正在加载..."
          :showIcon="true"
        ></uni-load-more>
        <uni-load-more
          v-if="status == '没有更多'"
          status="没有更多了"
          :showIcon="false"
        ></uni-load-more>
        <uni-load-more
          v-if="status == '暂无数据'"
          status="暂无数据"
          :showIcon="false"
        ></uni-load-more>
        <uni-load-more
          v-if="status == '请求失败'"
          status="加载失败，点我重试"
          :showIcon="false"
          @click="reLoad"
        ></uni-load-more>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState, mapGetters } from "vuex";
import yzbPosition from "@/components/yzb/yzb-position.vue";
import yzbResume from "@/components/yzb/yzb-resume.vue";
import yzbGrid from "@/components/yzb/yzb-grid.vue";
import companyList from "@/components/my-compents/company-list.vue";
import userList from "@/components/user-list/user-list.vue";
import IMService from "@/lib/imservice";
import amap from "@/common/amap-wx.js";
export default {
  components: {
    yzbPosition,
    yzbResume,
    yzbGrid,
    companyList,
    userList,
  },
  computed: {
    ...mapState(["userInfo"]),
    ...mapGetters(["hasLogin"]),
  },
  data() {
    return {
      statusBarHeight: 0,
      navBarHeight: 0,
      topHeight: 0,
      tabs: [
        {
          label: "职位",
          value: 1,
        },
        {
          label: "企业",
          value: 2,
        },
        {
          label: "中介",
          value: 3,
        },
      ],
      selectTab: 1,
      status: "",
      query: {
        page: 1,
        limit: 10,
      },
      banner: [],
      grid: [],
      ka: [],
      JobExpectList: [],
      list: [],
      selectExpected: null,
      key: "102dcab15e743584f73d383dea7530e7", //高德地图key
      location: {
        city: "未定位",
      }, //定位信息
      savedLocation: null, // 保存的位置信息

      loadStatus: "loading", //loading、fail、success
      noticeList: [],
      mConfig: {},
      imgUrl: "",
      companyList: [
        {
          companyName: "山西洪城运至科技有限公司",
        },
        {
          companyName: "山西小米科技有限公司",
        },
      ],
    };
  },
  created() {
    // 获取状态栏高度
    uni.getSystemInfo({
      success: (e) => {
        let statusBar = 0;
        let navbar = 0;
        
        // #ifdef MP-WEIXIN
        statusBar = e.statusBarHeight;
        const custom = wx.getMenuButtonBoundingClientRect();
        navbar = (custom.top - e.statusBarHeight) * 2 + custom.height;
        // #endif
        
        // #ifndef MP-WEIXIN
        statusBar = e.statusBarHeight;
        navbar = e.statusBarHeight + 45;
        // #endif
        
        this.statusBarHeight = statusBar;
        this.navBarHeight = navbar;
      }
    });
    
    // 初始化mConfig
    if (this.$mConfig) {
      this.mConfig = this.$mConfig;
      this.imgUrl = this.$mConfig.imageUrl || '';
    }
  },
  async onLoad(query) {
    console.log(query, "query");
    await this.$AppEntryController.main(query);
    this.getGrids();
    // 从缓存中获取保存的位置信息

   
  },

  onShow() {
    const savedLocation = uni.getStorageSync('savedLocation');
    if (savedLocation) {
      this.savedLocation = savedLocation;
    }
    this.$nextTick(() => {
      this.calculateTopHeight();
    });
  },
  
  mounted() {
    this.$nextTick(() => {
      this.calculateTopHeight();
    });
  },

  onPullDownRefresh() {
    this.getDatasByLoc("refresh", true);
  },

  onReachBottom() {
    this.getDatasByLoc("add");
  },
  methods: {
    // 计算顶部高度
    calculateTopHeight() {
      const query = uni.createSelectorQuery().in(this);
      query.select('.top').boundingClientRect(data => {
        if (data) {
          console.log('top高度：', data.height);
          this.topHeight = data.height;
        }
      }).exec();
    },
    
    //需要位置信息的
    getDatasByLoc(type = "refresh", pulldown = false) {
      console.log("memberRole===", this.userInfo.memberRole);
      if (this.location.pcitycode) {
        this.query.latitude = this.location.latitude;
        this.query.longitude = this.location.longitude;
        this.query.pcitycode = this.location.pcitycode;
        if (this.userInfo.memberRole == 1) {
          this.getResumeList(type, pulldown);
        } else {
          this.getPositionList(type, pulldown);
        }
      } else {
        console.log("位置不能为空哦");
      }
    },

    async roleChange() {
      //用户未绑定企业，角色切换
      if (this.userInfo.companyId == 0) {
        let res = await this.$apis.switchRole({
          role: 0,
        });
        this.getUserInfo();
      }
    },

    // 获取用户信息
    async getUserInfo() {
      let userInfo = await this.$apis.getUserInfo();
      if (userInfo == true) {
        uni.clearStorageSync();
        this.$store.commit("SET_LOGOUT");
        if (this.goEasy.getConnectionStatus() === "connected") {
          console.log("do  disconnect");
          getApp().globalData.imService.disconnect();
        }
        return;
      }
      this.$store.commit("SET_USERINFO", userInfo);
      this.getDatasByLoc();
    },
    initChat() {
      //注册
      if (this.hasLogin) {
        console.log(
          "this.goEasy.getConnectionStatus()==" + this.goEasy.getConnectionStatus()
        );
        if (this.goEasy.getConnectionStatus() === "disconnected") {
          getApp().globalData.imService = new IMService(this.goEasy, this.GoEasy);
          getApp().globalData.imService.connect(this.userInfo);
        } else {
          //加载会话列表
          this.goEasy.im.latestConversations({
            onSuccess: function (result) {
              let content = result.content;
              console.log("最新会话列表", content);
              let unreadTotal = content.unreadTotal;
              if (unreadTotal > 0) {
                uni.setTabBarBadge({
                  index: 2,
                  text: unreadTotal.toString(),
                });
              } else {
                uni.removeTabBarBadge({
                  index: 2,
                });
              }
            },
            onFailed: function (error) {
              //获取失败
              console.log(
                "失败获取最新会话列表, code:" + error.code + " content:" + error.content
              );
            },
          });
        }
      }
    },

    async getBanners() {
      let data = await this.$apis.getBanners({
        apId: 1,
      });
      if (data) {
        this.banner = data;
      }
    },

    async getPositionList(type = "refresh", pulldown = false) {
      this.status = "请求中";
      if (type == "refresh") {
        this.query.page = 1;
      } else {
        this.query.page++;
      }
      let res = await this.$apis.getPositionList(this.query);
      if (res) {
        if (type == "refresh") {
          this.list = [];
        }
        if (pulldown) {
          uni.stopPullDownRefresh();
        }
        let data = res.data;
        for (let i in data) {
          if (data[i].skill) {
            data[i].skill = data[i].skill.split(",");
          }
        }
        this.list = this.list.concat(data || []);
        this.changeStatus(res);
      }
    },

    async getResumeList(type = "refresh", pulldown = false) {
      this.status = "请求中";
      if (type == "refresh") {
        this.query.page = 1;
      } else {
        this.query.page++;
      }
      let res = await this.$apis.getResumeList(this.query);
      if (res) {
        if (type == "refresh") {
          this.list = [];
        }
        if (pulldown) {
          uni.stopPullDownRefresh();
        }
        let data = res.data;
        this.list = this.list.concat(data || []);
        this.changeStatus(res);
      }
    },

    // 修改请求状态
    changeStatus(data) {
      if (this.list.length === 0) {
        this.status = "暂无数据";
      } else if (this.query.page >= Math.ceil(data.count / this.query.limit)) {
        this.status = "没有更多";
      } else {
        this.status = "请求更多";
      }
    },

    getGrids() {
      this.grid = [
        {
          image: this.$mAssetsPath.grid_1,
          text: "最新发布",
          path: this.$mRoutesConfig.positionList,
          type: 1,
        },
        {
          image: this.$mAssetsPath.grid_2,
          text: "热招职位",
          path: this.$mRoutesConfig.positionList,
          type: 2,
        },
        {
          image: this.$mAssetsPath.grid_3,
          text: "高薪职位",
          path: this.$mRoutesConfig.positionList,
          type: 3,
        },
        {
          image: this.$mAssetsPath.grid_4,
          text: "兼职招聘",
          path: this.$mRoutesConfig.positionList,
          type: 4,
        },
        {
          image: this.$mAssetsPath.grid_5,
          text: "公司列表",
          path: this.$mRoutesConfig.companyList,
          type: 5,
        },

        {
          image: this.$mAssetsPath.grid_7,
          text: "特色课程",
          path: this.$mRoutesConfig.courseList,
          type: 4,
        },

        {
          image: this.$mAssetsPath.grid_9,
          text: "联系客服",
          path: this.$mRoutesConfig.contactUs,
          type: 5,
        },
        {
          image: this.$mAssetsPath.grid_10,
          text: "公告信息",
          path: this.$mRoutesConfig.notices,
          type: 5,
        },
      ];
    },

    handleClickGrid(o) {
      if (this.grid[o.index].type == 999) {
        uni.switchTab({
          url: "../type/type",
        });
        return;
      }
      console.log("handleClickGrid", this.grid[o.index]);
      this.$mRouter.push({
        route: this.grid[o.index].path,
        query: {
          type: this.grid[o.index].type,
          text: this.grid[o.index].text,
        },
      });
    },

    positionDetail(item) {
      this.$mRouter.push({
        route: this.$mRoutesConfig.positionDetail,
        query: {
          id: item.id,
        },
      });
    },

    resumeDetail(item) {
      this.$mRouter.push({
        route: this.$mRoutesConfig.resumeDetail,
        query: {
          id: item.id,
        },
      });
    },

    toAllPost() {
      uni.switchTab({
        url: "/pages/type/type",
      });
    },
    toPost(item) {
      //跳转到岗位筛选页面
      getApp().globalData.postId = item.id;
      uni.switchTab({
        url: "/pages/type/type",
      });
    },

    search() {
      this.$mRouter.push({
        route: this.$mRoutesConfig.search,
      });
    },

    toSelectCity() {
      console.log(this.$mRoutesConfig.selectCity,'this.$mRoutesConfig.selectCity')
      this.$mRouter.push({
        route: this.$mRoutesConfig.selectCity,
      });
      console.log("toSelectCity");
      // if (this.location.city == '未定位') {
      // 	//#ifdef MP-WEIXIN
      // 	this.locationAuth();
      // 	//#endif
      // } else {
      // uni.navigateTo({
      // 	url: '/pages/index/other/selectCity'
      // });
      // }
    },

    /**
     * 位置授权
     */
    locationAuth() {
      let that = this;
      uni.getSetting({
        success(res) {
          if (res.authSetting["scope.userLocation"]) {
            console.log("userLocation位置功能已授权");
            that.getLocation();
            // 如果已授权,直接获取对应参数
          } else if (!res.authSetting["scope.userLocation"]) {
            // 说明此时要获取的位置功能尚未授权,
            // 则设置进入页面时主动弹出，直接授权
            uni.authorize({
              scope: "scope.userLocation",
              success(res) {
                // 授权成功
                console.log(res);
                that.getLocation();
                // 成功后获取对应的位置参数
              },
              fail() {
                console.log("位置授权失败");
                uni.showModal({
                  content: "检测到您没打开获取信息功能权限，是否去设置打开？",
                  confirmText: "确认",
                  cancelText: "取消",
                  success: (res) => {
                    console.log(res);
                    if (res.confirm) {
                      uni.openSetting({
                        success: (res) => {
                          console.log("res", res);
                          that.getLocation();
                        },
                        fail: (err) => {
                          console.log(err);
                        },
                      });
                    } else {
                      console.log("取消");
                    }
                  },
                });
              },
            });
          }
        },
        fail() {
          console.log("获取授权信息授权失败");
        },
      });
    },

    getLocation() {
      //高德地图插件
      this.myAmapFun = new amap.AMapWX({
        key: this.key,
      });
      let that = this;
      this.myAmapFun.getRegeo({
        success: function (data) {
          //成功回调
          console.log("定位信息：", data);
          let mlocation = {
            latitude: data[0].latitude,
            longitude: data[0].longitude,
            pcity: data[0].regeocodeData.addressComponent.city,
            city: data[0].regeocodeData.addressComponent.district,
            citycode: data[0].regeocodeData.addressComponent.adcode + "000000",
            pcitycode:
              data[0].regeocodeData.addressComponent.adcode.substr(0, 4) + "00000000",
          };
          that.location = mlocation;
          getApp().globalData.location = mlocation;
          getApp().globalData.currentLocation = JSON.parse(JSON.stringify(mlocation));
          //保存到本地
          that.$db.set("location", mlocation);
          that.getDatasByLoc();
        },
        fail: function (info) {
          //失败回调
          console.log(info);
        },
      });
    },

    //获取定位信息
    getPosition() {
      console.log("=========获取定位信息========================");
      const that = this;
      uni.getLocation({
        type: "gcj02",
        success: function (lb) {
          console.log("位置信息", lb);
          console.log("当前位置的经度：" + lb.longitude);
          console.log("当前位置的纬度：" + lb.latitude);
          that.latitude = lb.latitude;
          that.longitude = lb.longitude;
          console.log(lb.longitude, lb.latitude);
          let key = "845d7a0716db36b612ce8e13369c4e09"; //高德地图key
          uni.request({
            // url: '/gaode?output=json&location=' + lb.longitude + ',' + lb.latitude + '&key=' + key + '&radius=1000&extensions=all',
            url:
              "/qq?output=json&location=" +
              lb.latitude +
              "," +
              lb.longitude +
              "&key=TZCBZ-R333W-T27RS-OX3SB-RRJET-AWFVF&radius=1000&get_poi=1",
            data: {},
            header: {
              "Content-Type": "application/json",
              "Access-Control-Allow-Origin": "*",
            },
            success: function (res) {
              console.log("高德地图API接口返回信息", res);
              // that.area = res.data.regeocode.addressComponent.city;
              console.log("定位信息：", res);
              let mlocation = {
                latitude: res.data.result.ad_info.location.latitude,
                longitude: res.data.result.location.longitude,
                pcity: res.data.result.ad_info.city,
                city: res.data.result.ad_info.district,
                citycode: res.data.result.ad_info.adcode + "000000",
                pcitycode: res.data.result.ad_info.adcode.substr(0, 4) + "00000000",
              };
              that.location = mlocation;
              getApp().globalData.location = mlocation;
              getApp().globalData.currentLocation = JSON.parse(JSON.stringify(mlocation));
              //保存到本地
              that.$db.set("location", mlocation);
              that.getDatasByLoc();
            },
          });
        },
        fail: function (error) {
          console.log("=======error=========", error);
        },
      });
    },

    listenCitySelect() {
      let that = this;
      uni.$on("city", (res) => {
        console.log("city", res);
        getApp().globalData.location.city = res.city;
        getApp().globalData.location.citycode = res.code;
        if (res.level == 2) {
          getApp().globalData.location.pcity = res.city;
          getApp().globalData.location.pcitycode = res.code;
        } else {
          getApp().globalData.location.pcity = res.pcity;
          getApp().globalData.location.pcitycode = res.pcode;
        }
        this.location = getApp().globalData.location;
        this.$db.set("location", this.location);
        this.getDatasByLoc();
      });
    },

    goItem(item) {
      console.log("goItem", item);
      this.$mRouter.push({
        route: this.$mRoutesConfig.noticeDetail,
        query: {
          id: item.noticeId,
        },
      });
    },

    goMore(item) {
      console.log("goMore", item);
      this.$mRouter.push({
        route: this.$mRoutesConfig.notices,
      });
    },
    changeTab(item) {
      this.selectTab = item;
    },
    toPost() {
      this.$mRouter.push({
        route: this.$mRoutesConfig.post,
        query: {
          id: 1,
        },
      });
    },
    gotoPer() {
      console.log("gotoPer 方法被调用");
      // 尝试使用多种导航方式
      try {
        uni.navigateTo({
          url: `/pages/user/person/resume?type=1`,
          success: function () {
            console.log("导航成功");
          },
          fail: function (err) {
            console.error("导航失败", err);
            // 如果第一种方式失败，尝试使用redirectTo
            uni.redirectTo({
              url: `/pages/user/person/resume?type=1`,
            });
          },
        });
      } catch (e) {
        console.error("导航异常", e);
      }
    },
  },
};
</script>
<style>
page {
  background: #f3f5fa;
}
</style>
<style lang="scss" scoped>
.top {
  position: fixed;
  top: 0;
  z-index: 100;
  width: 100%;
  color: #222222;
  font-size: 28rpx;
  background: #fff;
  padding-bottom: 20rpx;

  .page-title {
    font-size:40rpx;
    font-weight: bold;
    padding: 10rpx 30rpx;
  }

  .tabs-cont {
    margin: 15rpx 30rpx 0 30rpx;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .right-cont {
      display: flex;
      width: 100%;
      // justify-content: space-between;

      .select-item {
        background: #f3f5fa;
        padding: 15rpx 17rpx 15rpx 22rpx;
        border-radius: 10rpx;
        color: #9f9f9f;
        font-size: 28rpx;
        display: flex;
        align-items: center;
        margin-right: 10rpx;
        image {
          width: 16rpx;
          height: 16rpx;
          margin-left: 6rpx;
        }
      }
    }
  }
}

.navbar {
  height: 100upx;
  display: flex;
  align-items: flex-end;
  justify-content: center;

  text {
    margin-left: 20upx;
  }
}

// 搜索框
.mp-search {
  height: 92rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
  padding: 0 30rpx;
  box-sizing: border-box;
  margin-top: 10rpx;

  .mp-search-input {
    font-size: 28upx;
    background: #f3f5fa;
    width: 100%;
    padding: 18rpx 26rpx;
    padding-right: 60rpx;
    border-radius: 10rpx;
    display: flex;
    align-items: center;
    color: #aaa;
    position: relative;

    .icon-search {
      width: 32rpx;
      height: 32rpx;
      position: absolute;
      right: 26rpx;
    }
  }
}

.index-cont {
  background: #f3f5fa;
  padding: 20rpx;
}
</style>
